import { server$ } from '@builder.io/qwik-city';
import { type PostCollection } from '@prisma/client';
import { checkAuth } from '~/server/authn';
import { db } from '~/server/db';
import logger from '~/server/logger';
import { postCollectionService } from '~/server/service/post-collection-service';

const DEFAULT_COLLECTION_TIME = new Date(978278400000);
const DEFAULT_COLLECTION_ID = BigInt(0);

const defaultCollection = (userId: bigint): PostCollection => ({
  id: DEFAULT_COLLECTION_ID,
  userId,
  title: '未分类',
  createTime: DEFAULT_COLLECTION_TIME,
  updateTime: DEFAULT_COLLECTION_TIME,
  deleteTime: null,
});

export const findMyCollections = server$(async function () {
  const result = await checkAuth(this);
  if (!result.ok) {
    throw new Error('未登录');
  }

  const { userId } = result.data;
  const collections = await postCollectionService.findByUserId(db, userId);
  logger.info('[findMyCollections]', { userId: userId.toString(), resultCount: collections.length });
  return [...collections, defaultCollection(userId)];
});

export const createCollection = server$(async function (title: string) {
  const result = await checkAuth(this);
  if (!result.ok) {
    throw new Error('未登录');
  }

  const { userId } = result.data;
  return await postCollectionService.create(db, { userId, title });
});

export const updateCollection = server$(async function (id: bigint, title: string) {
  const result = await checkAuth(this);
  if (!result.ok) {
    throw new Error('未登录');
  }

  const { userId } = result.data;
  await db.$transaction(async (tx) => {
    const collection = await postCollectionService.findByIdAndUserId(tx, id, userId);
    if (!collection) {
      throw new Error('未找到分类');
    }

    await postCollectionService.update(tx, { id, userId, title });
  });
});
